package hw2.cs236369.solution;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Logging.Monitor;

import hw2.cs236369.WikiLinksFinder;

public class MyFinder implements WikiLinksFinder {

	@Override
	public Set<String> getWikiPageLinks(String fromURL) throws MalformedURLException {
		
		Set<String> $ = new LinkedHashSet<String>();
		Set<String> temp = new LinkedHashSet<String>();
		
		// creating the regular expressions to find the href links
		String op1 = "href[ ]*=[ ]*\"[^#][^\"]*\"";
		String op2 = "href[ ]*=[ ]*\'[^#][^\']*\'";
		Pattern linkPattern = Pattern.compile(op1 + "|" + op2);
		
		MyParser wikiParser  = new MyParser();
		// recognizing href-URLs 
		wikiParser.parseTags(fromURL);
		for (String curTag : wikiParser.getTags()) {
			Matcher linkMatcher = linkPattern.matcher(curTag);
			while(linkMatcher.find()){
				temp.add(linkMatcher.group());
			}
		}
		
		// removing "href=" prefixes & space trimming  
		String href = "href[ ]*=[ ]*";
		String gershaim = "\"";
		String geresh = "\'";
		
		Pattern trimmingPattern = Pattern.compile(href + "|" + geresh + "|" + gershaim);
		for(String s: temp)
		{
			Matcher trimmingMatcher = trimmingPattern.matcher(s);
			String trimedString = trimmingMatcher.replaceAll("");
			Monitor.write(this, "We are converting this string:"+s+" to:"+trimedString);
			
			// dealing with local references
			if (trimedString.startsWith("/") || trimedString.startsWith(".")){
				
				// getting the host name of the url
				URL siteAddress = new URL(fromURL);
				String host = siteAddress.getHost();
				trimedString = "http://" + host + trimedString;
			}
			// only saving strings that are 1 distance away
			if(trimedString.equals(fromURL)) continue;
			Monitor.write(this, "Adding the following link to our final set:"+trimedString);
			$.add(trimedString);
		}
		
		return $;
	}

}
